#pragma once
#include <cstdlib>
#include <memory>
#include<iostream>
#include<cstring>
#include <unistd.h>
#include <functional>
#include <sys/types.h>         
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "err.h"
#include "Threadpool.hpp"
#include "Task.hpp"
#include "log.hpp"



 using func_t = std::function<std::string(const std::string &)>;
 using namespace std;

class tcpServe;
class ThreadData
    {
    public:
        ThreadData(int fd, const std::string &ip, const uint16_t &port, tcpServe *ts)
        : sock(fd), clientip(ip), clientport(port), current(ts)
        {}
    public:
        int sock;  //接收连接后的文件描述符
        std::string clientip;  //客户端IP
        uint16_t clientport;   //客户端端口号
        tcpServe *current;  //服务器的this指针
    };

class tcpServe
{
public:
        static const uint16_t defaultport = 8081;
        static const int backlog = 32;
	  // 构造函数
       tcpServe(func_t func, uint16_t port = defaultport) : _func(func), _port(port),_quit(true)
        {
        }
      // 服务器初始化
      void initServer()
      {
        // 1. 创建socket文件
            _listensock= socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(Fatal, "create socket error, code: %d, error string: %s", errno, strerror(errno));
                exit(SOCKET_ERR);
            }
             logMessage(Info, "create socket success: %d", _listensock);

            // 2. bind
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = htonl(INADDR_ANY);
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                logMessage(Fatal, "bind socket error, code: %d, error string: %s", errno, strerror(errno));
                exit(BIND_ERR);
            }
            logMessage(Info, "bind socket success, code: %d", _listensock);
            // 3. 监听
            if (listen(_listensock, backlog) < 0)
            {
                logMessage(Fatal, "listen socket error, code: %d, error string: %s", errno, strerror(errno));
                exit(LISTEN_ERR);
            }
            logMessage(Info, "listen socket success, code: %d", _listensock);
      }
      static void *threadRoutine(void *args)
        {
            pthread_detach(pthread_self()); //线程分离，由操作系统回收线程资源

            ThreadData *td = static_cast<ThreadData *>(args);
            td->current->service(td->sock, td->clientip, td->clientport); //调用具体的服务函数
            delete td;
            return nullptr;
        }
      // 服务器运行
      void start()
      {
        //signal(SIGCHLD,SIG_IGN);

        _quit=false;
        while(!_quit){
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        // 4. 获取连接,accept
        int sock = accept(_listensock, (struct sockaddr *)&client, &len);
        if (sock < 0)
        {
             logMessage(Warning, "accept error, code: %d, error string: %s", errno, strerror(errno));
            continue;
        }
        // 提取client信息 -- debug
        std::string clientip = inet_ntoa(client.sin_addr);
        uint16_t clientport = ntohs(client.sin_port);
        // 5. 获取新连接成功, 开始进行业务处理
        logMessage(Info, "获取新连接成功: %d from %d, who: %s - %d",
                           sock, _listensock, clientip.c_str(), clientport);
        //v1:
        //service(sock,clientip,clientport);
        // //v2:多进程
        // pid_t id=fork();
        // if(id<0){
        //     close(sock);
        //     continue;
        // }
        // else if(id==0){ //child进程,父子进程不会用同一张文件描述符表，子进程拷贝继承父进程
        //     //建议关闭掉不需要的fd
        //     close(_listensock);
        //     if(fork()>0) exit(0);
        //     //子进程已经退了，孙子进程在进行
        //     service(sock,clientip,clientport);
        //     exit(0);
        // }
        // //父,一定关闭掉不需要的fd,不关闭，会导致fd泄漏
        // close(sock);
        // // pid_t ret=waitpid(id,nullptr,0);
        // // if(ret==id){
        // //     cout<<"wait child "<<id<<"success"<<endl;
        // // }
        // //v3. 多线程
        // pthread_t tid;
        // ThreadData *td = new ThreadData(sock, clientip, clientport, this); //存放服务器数据
        // pthread_create(&tid, nullptr, threadRoutine, td); //创建多线程

        //v4. 线程池
         Task t(sock, clientip, clientport, bind(&tcpServe::service, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        ThreadPool<Task>::getinstance()->pushTask(t);
    }
}
    void service(int sock,const std::string &clientip,const uint16_t &clientport)
        {
            std::string who = clientip + "-" + std::to_string(clientport);
            char buffer[1024];
            while (true)
            {
                ssize_t s = read(sock, buffer, sizeof(buffer) - 1); // 使用read从网络中读取数据
                if (s > 0)
                {
                    buffer[s] = 0;
                    std::string res = _func(buffer); // 进行回调
                    std::cout <<who<< " :recv message: " << res << std::endl;
                    logMessage(Debug, "%s# %s", who.c_str(), res.c_str());
                    write(sock, res.c_str(), res.size()); //使用write写入数据写回到网络中去
                }
                else if (s == 0)
                {
                    // 对方将连接关闭了
                    close(sock);
                    //std::cout <<who << " quit, me too" << std::endl;
                    logMessage(Info, "%s quit,me too", who.c_str());
                    break;
                }
                else
                {
                    close(sock);
                    //std::cerr << "read error: " << strerror(errno) << std::endl;
                    logMessage(Error, "read error, %d:%s", errno, strerror(errno));
                    break;
                }
            }
        }
      // 析构函数
      ~tcpServe()
      {}
private:
      int _listensock; // 不是用来进行数据通信的，是用来监听链接到来的，获取新连接
      uint16_t _port;
      func_t _func;
      bool _quit;
};
